package emailserving;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.security.ProtectionDomain;

public class EmbeddedJetty {
    private static final Logger logger = LoggerFactory.getLogger(EmbeddedJetty.class);
    private static final int DEFAULT_PORT = 8989;
    private static final String DEFAULT_PROFILE = "dev";

    public static void main(String[] args) throws Exception {
        ProtectionDomain domain = EmbeddedJetty.class.getProtectionDomain();
        URL location = domain.getCodeSource().getLocation();

        WebAppContext webapp = new WebAppContext();
        webapp.setDescriptor("WEB-INF/web.xml");
        webapp.setParentLoaderPriority(true);
        webapp.setContextPath("/");
        webapp.setWar(location.toExternalForm());

        // starts the embedded server and bind it on 8081 port
        Server server = new Server(getPortFromArgs(args));
        server.setHandler(webapp);
        server.start();
        server.join();
    }


    private static int getPortFromArgs(String[] args) {
        if (args.length > 0) {
            try {
                return Integer.valueOf(args[0]);
            } catch (NumberFormatException ignore) {
            }
        }
        logger.debug("No server port configured, falling back to {}", DEFAULT_PORT);
        return DEFAULT_PORT;
    }

}
